package com.xxwy.ddu.security.code.authentication.sms;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @author xxwy
 * on 2018/8/22 0022
 * 短信验证的额provider,由AuthenticationManager
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //获取用户信息
        //让用户信息去UserDetaileService-->得uSERDetail->认证的Token传入Session
        SmsCodeAuthenticationToken token = (SmsCodeAuthenticationToken) authentication;

        UserDetails userDetails = userDetailsService.loadUserByUsername((String) token.getPrincipal());

        if (userDetails == null) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(
                userDetails,userDetails.getAuthorities());
        //存放认知之前的用户信息this.setDetails(request, authRequest);
        authenticationResult.setDetails(token.getDetails());


        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        //让AuthenticationManager挑选SmsCodeAuthenticationToken来认证
        //判断传入的值是我们想要的Token吗
        return SmsCodeAuthenticationToken.class.isAssignableFrom(aClass);
    }

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
